<?php
/**
 * 托运单
 *
 *
 */
class shipping_list extends Controller
{

	/**
	 * 构造函数
	 *
	 * 登陆检验
	 */
	function __construct()
    {
        parent::Controller(); 
		if (!$this->session->userdata('logged_in')){          		
			redirect('login');
			exit();
		}
    }
    
	// --------------------------------------------------------------------

    /**
	 * 托运单列表
	 *
	 *
	 */	
    function index()
    {


        // 接收客户端反馈的信息： ajax，post
		$field = ($this->input->post('field')) ? ($this->input->post('field')) : 0;
		$keyword = ($this->input->post('keyword')) ? $this->input->post('keyword') : 0;
		$search = $this->input->post('search');
		$page = $this->input->post('page'); $page = (int)$page;
		$start_time = $this->input->post('st');
		$end_time	= $this->input->post('et');      
		$checkin_site =   $this->input->post('checkin_site');
		$destination_site  =  $this->input->post('destination_site');              
		// 分页+查询的url设置
        $segments = $this->uri->uri_to_assoc();
        
		if ($search){
			$segments['field'] = $field;
			$segments['keyword'] = $keyword;			
		}else{
			$segments['field'] = !empty($segments['field']) ? $segments['field'] : 0;
			$segments['keyword'] = !empty($segments['keyword']) ? $segments['keyword'] : 0;
		}			       	
		$search_uri = '/' . $segments['field'] . '/' . $segments['keyword'];
		
		
		 
		//计算查询条件
        $options = array(
            'conditions' => null,
        );


        $data['keyword'] = '';
         
        
 
        //  按关键字查询
		if (!empty($segments['keyword'])){
           
                $options['conditions'][$segments['field']] = $segments['keyword'] ;
                $options['conditions']['st'] = $start_time;
                $options['conditions']['et'] = $end_time;
                if ($checkin_site != 0 )  $options['conditions']['checkin_site'] = $checkin_site;
                if ($destination_site != 0 ) $options['conditions']['destination_site'] = $destination_site;                
                $data['keyword'] =$segments['keyword'];
           
        }

    
	    // 分页的开始数据行：$page_offset
		if($page){
            $page_offset = $page-1;
		}else if (!empty($segments['page'])){
            $page_offset = (int)$segments['page'];		
        } else {
            $page_offset = 0;
        }
		if ($page_offset<0){
            $page_offset=0;
		}
		
		// 分页url
		$base_url = site_url('shipping_list/index/page') . '/';

		// 每页显示数据条数
        $per_page = 14;
        
		// 数据总数
		$this->load->model('shipping_list_model');	
			
		$data['total_rows'] =  $this->shipping_list_model->count_shipping_lists($options);
 		 
		// 总页数
        $data['total_pages'] = ceil($data['total_rows']/$per_page);
        
		// 当前页（input）
        $data['page'] = $page_offset+1;
		$data['page'] = ($data['page']>$data['total_pages'] && $data['total_pages']>0) ? $data['total_pages'] : $data['page'];

		// 第一页 最后一页 前一页 后一页
		$data['page_first'] = $base_url.'0'.$search_uri;
		$data['page_last'] = $base_url.($data['total_pages']-1).$search_uri;
		$data['page_prev'] = ($data['page']>1) ? $base_url.($data['page']-2).$search_uri : $data['page_first'];
	    $data['page_next'] = ($data['page']<$data['total_pages']) ? $base_url.($data['page']).$search_uri : $data['page_last'];

		// 当前页
		$data['cur_page'] =  $base_url.($data['page']-1).$search_uri;
		
		// 当前页起始数据号
		$data['show_start'] = ($data['page']-1)*$per_page+1;

		// 当前页结束数据号
		$data['show_end'] = ($page_offset<$data['total_pages']-1) ? ($data['show_start']+$per_page-1) : $data['total_rows'];

	    // 托运单结果集
		$data['shipping_list'] = $this->shipping_list_model->find_shipping_lists($options, $per_page, ($data['page']-1)*$per_page);
    //echo 'sql'.$this->db->last_query();
		// 发站代码
		$this->load->model('code_checkedin_site_model');
		$data['checkedin_site'] = $this->code_checkedin_site_model->get_all();
		// 到站代码
		$this->load->model('code_destination_site_model');
		$data['destination_site'] = $this->code_destination_site_model->get_all();
		
        $this->firephp->log($data);
	    //$data['editing']['indexed_org_string'] = $this->code_indexed_org_model->get_list($data['editing']['indexed_organization']);              

		// ajax 
		if (!empty($segments['ajax']) || $search==1){
			$this->load->view('shipping_list/shipping_list/ajax_list',$data);
		// 非 ajax
		}else{
            $this->load->view('shipping_list/shipping_list/list',$data);
		}
    }
    
	// --------------------------------------------------------------------

    /**
	 * 添加托运单
	 *
	 *
	 */	  
	function add()
    {
        $this->edit();
    }
    
	// --------------------------------------------------------------------

    /**
	 * 编辑托运单
	 *
	 *
	 */	  
	function edit()
    {
		// 检验操作权限
		if (!admin_priv('shipping_list_manage')){
			return show_message2('你没有此项操作的权限!', 'shipping_list');
		}

		$params = $this->uri->uri_to_assoc();
        if (!empty($params['id']) && $params['id'] > 0){
            $id = $params['id'];
            $this->load->model('shipping_list_model');
            $data['editing'] = $this->shipping_list_model->load($id);
            $this->firephp->log($data);
			if (!$data['editing']){
                return show_message2('无效ID:'.$id, 'shipping_list');
            }
            
 
	 
			        
			$data['header_text'] = '编辑托运单(ID:'.$data['editing']['id'].')';
        } else {

        	$this->load->model('sys_parameter_model');
        	$current_shipping_no = $this->sys_parameter_model->load('current_shipping_no');        	
        	$seq = substr($current_shipping_no['value'],8);
        	
			
        	$shipping_no  = date('Ymd',time());
        	$cur_date = substr($current_shipping_no['value'],0,8);	
            if ($shipping_no >  $cur_date)
            {
            	$shipping_no =  $shipping_no.'00000';
            } elseif ($shipping_no == $cur_date)
            {
            	$shipping_no = $shipping_no.sprintf('%05s', strval($seq+1));
            }
            $this->sys_parameter_model->value = $shipping_no;
            $this->sys_parameter_model->name = 'current_shipping_no';
            $this->sys_parameter_model->update('current_shipping_no');
 
            $data['editing'] = array(

                     'id' =>null,
            		'shipping_no'   => $shipping_no,
            		
            		'shipper'   => null,
            		
            		'shipper_telephone'   => null,
            		
            		'receiver'   => null,
            		
            		'receiver_telephone'   => null,
            		
            		'delivery_methmod'   => null,
            		
            		'payment_mode'   => null,
            		
            		'goods_name'   => null,
            		
            		'goods_num'   => null,
            		
            		'goods_packet_num'   => null,
            		
            		'goods_value'   => null,
            		
            		'transfer_station'   => null,
            		
            		'freight'   => null,
            		
            		'cod_fee'   => null,
            		
            		'actual_fee'   => null,
            		
            		'transfer_fee'   => null,
            		
            		'checkin_site'   =>  $this->session->userdata('site'),
            		
            		'destination_site'   => null,

            		'operator' =>  $this->session->userdata('id'),
            		
            		'operate_datetime'   => date('Y年m月d日',time()),
            		
            		'demo'   => null,
            		'v_fee'  =>null,
            		
 				
            );
            
		 

			$data['header_text'] = '添加托运单';
        }
      
	 
           
 
       // 发站代码
       $this->load->model('code_checkedin_site_model');
       $data['checkedin_site'] = $this->code_checkedin_site_model->get_all();        
       // 到站代码
       $this->load->model('code_destination_site_model');
       $data['destination_site'] = $this->code_destination_site_model->get_all();

       // 付款方式代码
       $this->load->model('code_payment_mode_model');
       $data['payment_mode'] = $this->code_payment_mode_model->get_all();
        
       // 服务方式代码
       $this->load->model('code_delivery_methmod_model');
       $data['delivery_methmod'] = $this->code_delivery_methmod_model->get_all();
       
       // 服务方式代码
       $this->load->model('code_transfer_station_model');
       $data['transfer_station'] = $this->code_transfer_station_model->get_all();
       
       //开票人列表
        $this->load->model('admin_user_model');
       $data['user'] = $this->admin_user_model->get_all();
       
     
        
       $this->load->view('shipping_list/shipping_list/edit',$data);
       

    }
    
    // --------------------------------------------------------------------

    /**
	 * 提交数据
	 *
	 *
	 */	  
    function save()
    {

    	 
    	$this->load->helper('pinyin');

	    
    	// 保存后并继续编辑信号
		$re_edit = $this->input->post('re_edit');

        // 托运单id
        $id = $this->input->post('id');
        
    
	    $shipping_no    = $this->input->post('shipping_no');
        
        $shipper    = $this->input->post('shipper');
        $shipper_pinyin =      GetPinyin($shipper,1,0);
        
        $shipper_telephone    = $this->input->post('shipper_telephone');
        
        $receiver    = $this->input->post('receiver');
        $receiver_pinyin =      GetPinyin($receiver,1,0);        
        $receiver_telephone    = $this->input->post('receiver_telephone');
        
        $delivery_methmod    = $this->input->post('delivery_methmod');
        
        $payment_mode    = $this->input->post('payment_mode');
        
        $goods_name    = $this->input->post('goods_name');
        
        $goods_num    = $this->input->post('goods_num');
        
        $goods_packet_num    = $this->input->post('goods_packet_num');
        
        $goods_value    = $this->input->post('goods_value');
        
        $transfer_station    = $this->input->post('transfer_station');
        
        $freight    = $this->input->post('freight');
        
        $cod_fee    = $this->input->post('cod_fee');
        $v_fee    = $this->input->post('v_fee');
		if (empty($id) || $id == 0 )
		{
        	$actual_fee    = $this->input->post('cod_fee');
		}else {
			$actual_fee    = $this->input->post('actual_fee');			
		}
        $transfer_fee    = $this->input->post('transfer_fee');
        
        $checkin_site    = $this->input->post('checkin_site');
        
        $destination_site    = $this->input->post('destination_site');
        
        $operator    = $this->input->post('operator');
        
        $operate_datetime  =   $this->input->post('operate_datetime');       
        $demo   = $this->input->post('demo');
        $v_fee   = $this->input->post('v_fee');
        

        
	    // 加载表单验证类
        $this->load->library('validation');


        
		// 如果提交数据符合所设置的规则，则继续运行
		 
 
			//把数据提交给模型
            $this->load->model('shipping_list_model');         
            $this->shipping_list_model->id = $id;
            $this->shipping_list_model->shipping_no    = $shipping_no;
            $this->shipping_list_model->shipper    = $shipper;
            $this->shipping_list_model->shipper_telephone    = $shipper_telephone;
            $this->shipping_list_model->receiver    = $receiver;
            $this->shipping_list_model->receiver_telephone    = $receiver_telephone;
            $this->shipping_list_model->delivery_methmod    = $delivery_methmod;
            $this->shipping_list_model->payment_mode    = $payment_mode;
            $this->shipping_list_model->goods_name    = $goods_name;
            $this->shipping_list_model->goods_num    = $goods_num;
            $this->shipping_list_model->goods_packet_num    = $goods_packet_num;
            $this->shipping_list_model->goods_value    = $goods_value;
            $this->shipping_list_model->transfer_station    = $transfer_station;
            $this->shipping_list_model->freight    = $freight;
            $this->shipping_list_model->cod_fee    = $cod_fee;
            $this->shipping_list_model->actual_fee    = $actual_fee;
            $this->shipping_list_model->transfer_fee    = $transfer_fee;
            $this->shipping_list_model->checkin_site    = $checkin_site;
            $this->shipping_list_model->destination_site    = $destination_site;
            $this->shipping_list_model->operator    = $operator;
            $this->shipping_list_model->operate_datetime  =   $operate_datetime;
            $this->shipping_list_model->demo   = $demo;
            $this->shipping_list_model->v_fee   = $v_fee;
    
            
			 

			//更新
            if ($id){
                $old_pro = $this->shipping_list_model->load($id);
                $this->shipping_list_model->update($id);
				$new_pro = $this->shipping_list_model->load($id);

			 
		          
				//继续编辑
				if($re_edit){ 
				   //echo $id;
                    show_message2('"托运单(ID:'.$id.')" 已更新!', 'shipping_list/edit/id/'.$id);
			    //返回列表
			    }else{ 
				    //echo '更新成功';
					show_message2('"托运单(ID:'.$id.')" 已更新!', 'shipping_list');
				}
				
            // 添加新托运单
            } else {
                $this->shipping_list_model->create();

					 

			
			   if ($re_edit){
				   //echo $newly_one['id'];
                   show_message2('"托运单(ID:'.$newly_one['id'].')" 已保存!', 'shipping_list/edit/id/'.$newly_one['id']);
			   }else{
				   //echo '保存成功!';
				   	$this->load->model('shipping_user_model');
				   	$shipping_user = $this->shipping_user_model->load_all($shipper_pinyin,$shipper_telephone,'shipper');
				   	if (empty($shipping_user)||count($shipping_user) == 0)
				   	{
				   		$this->shipping_user_model->name_pingyin= $shipper_pinyin;
				   		$this->shipping_user_model->name = $shipper;
				   		$this->shipping_user_model->telephone =$shipper_telephone;
				   		$this->shipping_user_model->type ='shipper';
				   		$this->shipping_user_model->create();
				   	}
				   	
				   	$this->load->model('shipping_user_model');
				   	$shipping_user = $this->shipping_user_model->load_all($shipper_pinyin,$shipper_telephone,'receiver');
				   	if (empty($shipping_user)||count($shipping_user) == 0)
				   	{
				   		$this->shipping_user_model->name_pingyin= $receiver_pinyin;
				   		$this->shipping_user_model->name = $receiver;				   		
				   		$this->shipping_user_model->telephone =$receiver_telephone;
				   		$this->shipping_user_model->type ='receiver';
				   		$this->shipping_user_model->create();
				   	}				   	
				    show_message3('保存成功!', 'shipping_list/print_shipping2/id/'.$shipping_no);
			   }
			}
   
		
		 
				
	}

    // --------------------------------------------------------------------

    /**
	 * 删除托运单
	 *
	 *
	 */	
    function delete()
    {
		 // 检验操作权限
		if (!admin_priv('shipping_list_delete')){
			return show_message2('你没有此项操作的权限!', 'shipping_list');
		}
		$this->load->model('shipping_list_model');
			

		$params = $this->uri->uri_to_assoc();

        if (isset($params['id']) && ($id = $params['id']) > 0){
        	$site =  $this->shipping_list_model->get_checkin_site($params['id']);
		    if ($this->session->userdata('name') != 'admin' && $this->session->userdata('site') != $site)
		    {
		    	return show_message2('非管理员无法删除其他站点托运单！', 'shipping_list');		    	
		    }

			// 删除托运单
            $this->load->model('shipping_list_model');
            if ($this->shipping_list_model->delete($id)){
                //echo $id;
				show_message2('"托运单(ID:'.$id.')" 已被删除!', 'shipping_list');
            } else {
                //return false;
				return show_message2('无效ID:'.$id, 'shipping_list');
            }
        }
	}

    // --------------------------------------------------------------------

 
 
	
 	/**
 	 * 表单UID字段检查
 	 * 大于0返回TRUE
 	 *否则返回FALSE
 	 */
     function uid_check($str){
     	$this->firephp->log("我执行了");
     	
     	if ((int)$str > 0){
     		return TRUE;
     	}else 
     	{
     		$this->validation->set_message('uid_check','数组');
     		return FALSE;
     	}
     }

 

	

	// --------------------------------------------------------------------

    /**
	 * 托运单列表的单个字段编辑  ajax
	 *
	 */	
	function list_toggle()
	{
        $segments = $this->uri->uri_to_assoc();
		$field = $segments['field'];
		$shipping_list_id = (int)$segments['id'];
		$val = $segments['val'];
		$this->load->model('shipping_list_model');
        if ($value = $this->shipping_list_model->update_one(array($field => $val),$shipping_list_id)){
			echo $value;
		}
	}
	
	/*
	 * 报表打印
	 */ 
	   
	function report()
	{
		$start_time = $this->input->post('st');
		$end_time	= $this->input->post('et');      
		//$checkin_site =   $this->input->post('checkin_site');
		
		$destination_site  =  $this->input->post('destination_site');	
		
		$report_type  = $this->input->post('report_type');
		$search = $this->input->post('search');
		//计算查询条件
		$options = array(
				'conditions' => null,
		);
		
		
		

		$data = array();
	 
		// 
		$destination_site_array = array('id'=>null,'name'=>null);
		 
		$this->load->model('shipping_list_model');
		$data['shipping_list'] = $this->shipping_list_model->find_shipping_lists_report($start_time,$end_time,$report_type,$destination_site);
		
		
		$data['shipping_list_sum_fee'] = $this->shipping_list_model->find_shipping_lists_report_paymentmode($start_time,$end_time,$report_type,$destination_site);		
		
		$this->load->model('code_destination_site_model');
		$data['start_time']=$start_time;
		$data['end_time'] =$end_time;
		$destination_site_array = $this->code_destination_site_model->load($destination_site);
		
		$data['destination_site'] = $destination_site_array['name'] ;
		if ($report_type ==1) {

			$this->load->view('shipping_list/shipping_list/report_shipping_list',$data);
		}elseif ( $report_type ==2)
		{
			$this->load->view('shipping_list/shipping_list/report_cod_fee',$data);			
		}
	
	}
	/*
	 * 打印托运单
	 */
	function print_shipping()
	{
		$params = $this->uri->uri_to_assoc();
        $id =$params['id'];	
        
        $this->load->model('sys_parameter_model');
        $parameter = $this->sys_parameter_model->find_sys_parameter();
        
		$data = array();
		//
		$destination_site_array = array();
		$this->load->model('shipping_list_model');
		$data['shipping'] = $this->shipping_list_model->load_shipping($id);
		$data['parameter']  =$parameter;
		$this->load->view('shipping_list/shipping_list/print_shipping',$data);
	}
	
	
	
	function print_shipping2()
	{
		$params = $this->uri->uri_to_assoc();
		$id =$params['id'];
	
		$this->load->model('sys_parameter_model');
		$parameter = $this->sys_parameter_model->find_sys_parameter();
	
		$data = array();
		//
		$destination_site_array = array();
		$this->load->model('shipping_list_model');
		$data['shipping'] = $this->shipping_list_model->load_shipping($id);
		$data['parameter']  =$parameter;
		$this->load->view('shipping_list/shipping_list/print_shipping2',$data);
	}
		
	
	/**
	 * 自动完成
	 */
	function auto_complete(){
			$v=$this->input->post('value');
			$type=$this->input->post('type');
			$this->load->model('shipping_user_model');
			$query = $this->shipping_user_model->load($v,$type);
            
			if(count($query)<=0) exit('0');
			echo '<ul>';
			foreach ($query->result() as $row)
			{
				echo '<li onclick=auto_set("'.$type.'","'.$row->name.'","'.$row->telephone.'")><div id="name">'.$row->name.'</div>    <div id="telephone">'.$row->telephone.'</div></li>';
			}			
			 
			 
			echo '</ul>';
	}
	
}